package com.zyd.androidwifi;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.hb.dialog.myDialog.MyAlertInputDialog;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.zyd.androidwifi.adapter.WifiListAdapter;
import com.zyd.androidwifi.bean.WifiBean;
import com.zyd.androidwifi.utils.HandlerUtils;
import com.zyd.androidwifi.utils.WifiManagerUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WiFiActivity extends AppCompatActivity implements HandlerUtils.OnReceiveMessageListener {


    //url:https://github.com/ThanosFisherman/WifiUtils.git
    // 权限请求码
    private static final int PERMISSION_REQUEST_CODE = 0;
    // 两个权限需要动态申请
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
    };

    private HandlerUtils.HandlerHolder handlerUtils;

    //view
    private RecyclerView recycleview;
    private Switch switchBt;


    @SuppressLint("WifiManagerLeak")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wi_fi);

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 555);
            return;

        }

        // SSID 扫描wifi
        // SSID 扫描wifi
        // new ConnectionManager(WiFiActivity.this).scanWithWAP();

        // 新方法连接wifi
        // new ConnectionManager(WiFiActivity.this).connectWifiWithWAP(wifiName3, wifiPassword3);

        // 取消正在连接的wifi
        // new ConnectionManager(WiFiActivity.this).cancelConnectWithWAP(wifiName3, wifiPassword3);

        // 这个bssid是扫描扫出来的，跟ssid对应 ，ssid其实就是wifi名称
        // new ConnectionManager(WiFiActivity.this).wpsConnectWithWAP("54:a7:03:dd:9e:96", wifiPassword3);

        // 断开连接wifi
        // new ConnectionManager(WiFiActivity.this).disConnectWithWAP();
        // 不保存且断开链接
        // new ConnectionManager(WiFiActivity.this).disConnectDeleteWithWAP(wifiName3);

        init();

    }

    /**
     * 判断权限
     * 是否通过，
     * 如果通过
     * 就初始化
     */
    private boolean mHasPermission; // 是否通过权限

    private void init() {

        mHasPermission = checkPermission();
        if (!mHasPermission) {
            // 未获取权限，申请权限
            Toast.makeText(WiFiActivity.this, "未获取权限，申请权限", Toast.LENGTH_SHORT).show();
            requestPermission();

        } else if (mHasPermission) {
            // 已经获取权限
            //new ConnectionManager(WiFiActivity.this).openWithWAP();
            Toast.makeText(WiFiActivity.this, "已经获取权限", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(WiFiActivity.this, "WIFI处于关闭状态", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.d("mogut","====requestCode===="+requestCode+"===data=="+data.toString());
    }

    /**
     * 申请
     * 权限
     */
    private void requestPermission() {
        ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, PERMISSION_REQUEST_CODE);
    }

    /**
     * @return 检查
     * 是否
     * 已经
     * 授予权限
     */
    private boolean checkPermission() {
        for (String permission : NEEDED_PERMISSIONS) {
            if (ActivityCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        initView();
    }

    /**
     * 初始化
     * view
     */
    private List<WifiBean> mList = new ArrayList<>();
    private HandlerUtils.HandlerHolder myHandler;
    private static final int MSG_WIFI_TAG = 0x11111;//连接WiFi成功
    private static final int MSG_WIFI_TWO = 0x11112;//消息标记

    private WifiListAdapter wifiListAdapter;
    private WifiManager wifiMgr;//wifi管理

    @SuppressLint("WifiManagerLeak")
    private void initView() {
        Toast.makeText(WiFiActivity.this, "蘑菇头", Toast.LENGTH_SHORT).show();

        handlerUtils = new HandlerUtils.HandlerHolder(this);
        mWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        scanResults = new ArrayList<>();

        recycleview = findViewById(R.id.recycleview);
        switchBt = findViewById(R.id.switch_bt);

        LinearLayoutManager managerVertical = new LinearLayoutManager(WiFiActivity.this);
        managerVertical.setOrientation(LinearLayoutManager.VERTICAL);

        recycleview.setLayoutManager(managerVertical);
        recycleview.setHasFixedSize(true);


        //选择
        switchBt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                Log.d("TAG", "=====isChecked======" + isChecked);

                if (isChecked) {//打开WiFi
                    //执行ui线程
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            LoginDialogUtil.getInstance().showLoadingDialog(WiFiActivity.this, "Wifi扫描中...");
//                        }
//                    });

                    //Toast.makeText(WiFiActivity.this, "开始扫描", Toast.LENGTH_LONG).show();
                    switchBt.setSwitchPadding(2);
                    openWifi();

                } else {  //关闭wifi

                    //执行ui线程
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WiFiActivity.this, "关闭扫描", Toast.LENGTH_LONG).show();
                        }
                    });

                    switchBt.setSwitchPadding(1);
//                    new ConnectionManager(WiFiActivity.this).closeWithWAP();
                    wifiMgr.setWifiEnabled(false);
                    mList.clear();
                    //执行ui线程
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            wifiListAdapter.notifyDataSetChanged();
                        }
                    });

                }
            }
        });

        wifiListAdapter = new WifiListAdapter(this, mList);

        recycleview.setAdapter(wifiListAdapter);

        wifiMgr = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //接口回调
        wifiListAdapter.setMyOnItemClickListener(new WifiListAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                //连接wifi
//                Log.d("TAG", "====position=====" + mList.get(position).getWifiName());

                final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(WiFiActivity.this).builder()
                        .setTitle("请输入wifi" + mList.get(position).getWifiName() + "密码")
                        .setEditText("");
                myAlertInputDialog.setPositiveButton("确认", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        LoginDialogUtil.getInstance().showLoadingDialog(WiFiActivity.this, "Wifi连接中...");//开启加载动画
//                        Log.d("TAG", "===请输入wifi===" +
//                                mList.get(position).getWifiName() +
//                                "======" + myAlertInputDialog
//                                .getContentEditText()
//                                .getText()
//                                .toString().trim());

                        wifiUserName = mList.get(position).getWifiName().trim();
                        wifiPassWord = myAlertInputDialog
                                .getContentEditText()
                                .getText()
                                .toString().trim();

                        conutNum = 0;//计数wifi连接次数
                        connectStateTag = 0;
                        handlerUtils.sendEmptyMessageDelayed(MSG_WIFI_TAG, 100);

                        myAlertInputDialog.dismiss();

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        myAlertInputDialog.dismiss();
                    }
                });
                myAlertInputDialog.show();

            }

            @Override
            public void OnItemLonClick(int position) {

            }
        });

    }

    /**
     * 打开
     * 网络
     */
    private void openWifi() {
//        new ConnectionManager(WiFiActivity.this).openWithWAP();
        wifiMgr.setWifiEnabled(true);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Looper.prepare();
                    Thread.sleep(300);
                    scanWithWAP();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();
    }


    /**
     * 扫描
     * wifi
     */
    private WifiManager mWifi;
    private List<ScanResult> scanResults;

    public void scanWithWAP() {

        scanResults.clear();

        WifiManagerUtils.startScanWifi(mWifi);
        scanResults = WifiManagerUtils.getScanResult(mWifi);

        mList.clear();

        for (int i = 0; i < scanResults.size(); i++) {
            //SSID:wifi名字
            //加密方式:capabilities
            //信号强度:level
            if (!scanResults.get(i).SSID.isEmpty() && scanResults.get(i).SSID != "") {
                WifiBean wifiBean = new WifiBean();

                wifiBean.setWifiName(scanResults.get(i).SSID);
                wifiBean.setState("未连接");
                wifiBean.setBsssiD(scanResults.get(i).BSSID);
                wifiBean.setCapabilities(scanResults.get(i).capabilities);
                wifiBean.setLevel(scanResults.get(i).level);
                mList.add(wifiBean);

            }

        }

        Set<WifiBean> userSet = new HashSet<>(mList);
        mList.clear();
        List<WifiBean> mist = new ArrayList<>(userSet);

        mList.addAll(mist);

        Collections.sort(mList);

        handlerUtils.sendEmptyMessage(MSG_WIFI_TWO);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private int conutNum = 0;//wifi连接次数统计
    private int connectStateTag = 0;

    @Override
    public void handlerMessage(Message msg) {
        switch (msg.what) {
            case MSG_WIFI_TAG://连接
                conutNum = conutNum + 1;

                if (conutNum > 5) {
                    Toast.makeText(WiFiActivity.this, "wifi连接失败", Toast.LENGTH_LONG).show();
//                    LoginDialogUtil.getInstance().closeLoadingDialog();//关闭对话框
                    return;
                }
                if (WifiUtils.withContext(WiFiActivity.this).isWifiConnected() && connectStateTag > 0) {
                    Toast.makeText(WiFiActivity.this, "wifi连接成功", Toast.LENGTH_LONG).show();
//                    LoginDialogUtil.getInstance().closeLoadingDialog();//关闭对话框
                } else {

                    handlerUtils.sendEmptyMessageDelayed(MSG_WIFI_TAG, 2000);
                    connectWiFi(wifiUserName, wifiPassWord);
                }

                break;
            case MSG_WIFI_TWO://扫描
//                Log.d("TAG", "======刷新数=====" + mList.size());

                if (scanResults.size() == 0) {
                    scanWithWAP();
                }

                wifiListAdapter.setVerticalDataList(mList);
//                LoginDialogUtil.getInstance().closeLoadingDialog();//关闭动画

                break;
            default:
                break;
        }
    }

    /**
     * 连接
     * WiFi
     */
    private String wifiUserName = "";
    private String wifiPassWord = "";

    private void connectWiFi(String name, String passWord) {
        WifiConfiguration wifiCong = new WifiConfiguration();
        wifiCong.SSID = "\"" + name.trim() + "\"";//\"转义字符，代表"
        wifiCong.preSharedKey = "\"" + passWord.trim() + "\"";//WPA-PSK密码

        wifiCong.hiddenSSID = false;
        wifiCong.status = WifiConfiguration.Status.ENABLED;
        int resstate = wifiMgr.addNetwork(wifiCong);//107将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态，成功返回ID，否则为-1
//        Log.d("TAG", "====WIFI密码信息添加状态=====" + resstate);
        connectStateTag = resstate;
        if (resstate == -1) {
//            Log.d("TAG", "===再添加一次===WIFI密码信息添加状态===" + resstate);
            wifiMgr.addNetwork(wifiCong);

        } else {

            //wifi连接成功
        }
    }
}
